package com.gooluke.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolConfig {

    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();

    // ========== IO密集型线程池配置 ==========
    // IO密集型任务（如网络请求、数据库操作）线程数可以设置大些
    private static final int IO_CORE_POOL_SIZE = CORE_POOL_SIZE * 2;
    private static final int IO_MAX_POOL_SIZE = CORE_POOL_SIZE * 4;
    private static final int IO_QUEUE_CAPACITY = 1000;
    private static final String IO_THREAD_NAME_PREFIX = "io-thread-";

    // ========== CPU密集型线程池配置 ==========
    // CPU密集型任务（如计算、数据处理）线程数不宜过多
    private static final int CPU_CORE_POOL_SIZE = CORE_POOL_SIZE;
    private static final int CPU_MAX_POOL_SIZE = CORE_POOL_SIZE + 1;
    private static final int CPU_QUEUE_CAPACITY = 100;
    private static final String CPU_THREAD_NAME_PREFIX = "cpu-thread-";

    /**
     * IO密集型线程池（处理网络请求、数据库操作等）
     */
    @Bean("ioThreadPoolTaskExecutor")
    public Executor ioThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(IO_CORE_POOL_SIZE);
        executor.setMaxPoolSize(IO_MAX_POOL_SIZE);
        executor.setQueueCapacity(IO_QUEUE_CAPACITY);
        executor.setThreadNamePrefix(IO_THREAD_NAME_PREFIX);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setKeepAliveSeconds(60);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    /**
     * CPU密集型线程池（处理计算密集型任务）
     */
    @Bean("cpuThreadPoolTaskExecutor")
    public Executor cpuThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CPU_CORE_POOL_SIZE);
        executor.setMaxPoolSize(CPU_MAX_POOL_SIZE);
        executor.setQueueCapacity(CPU_QUEUE_CAPACITY);
        executor.setThreadNamePrefix(CPU_THREAD_NAME_PREFIX);
        // CPU密集型任务使用AbortPolicy，避免任务堆积
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 不需要keepAlive，因为CPU密集型线程数固定
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    /**
     * 通用线程池（备用）
     * 真的需要吗？？在什么场景下会用到？
     */
    @Bean("commonThreadPoolTaskExecutor")
    public Executor commonThreadPoolTaskExecutor() {
        return Executors.newCachedThreadPool();
    }
}